<template>
  <div style="padding:20px">
    <h1>{{id ? '编辑':'新建'}}分类</h1>
    <el-form label-width = "120px" :rules = "rule" ref = "FormRef" :model = "model">
      <el-form-item label = "【分类名称】" prop = "name">
        <el-input v-model="model.name" placeholder = "请输入分类名称" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item label = "【请求路径】" prop = "path">
        <el-input v-model="model.path" placeholder = "请输入请求路径" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item label = "【分类图标】" prop = "icon">
        <el-input v-model="model.icon" placeholder = "请输入分类图标" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type = 'primary' @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['id'],
  data () {
    return {
      model: {
        name: '',
        path: '',
        icon: ''
      },
      rule: {
        name:
          {
            required: true,
            message: '请填写分类名称',
            trigger: 'blur'

          },
        path: {
          required: true,
          message: '请填写请求路径',
          trigger: 'blur'
        },
        icon: {
          required: true,
          message: '请填写分类图标',
          trigger: 'blur'
        }

      }
    }
  },
  methods: {
    async save () {
      this.$refs.FormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.warning('请正确填写所有相关信息')
        }
        const res = this.id ? await this.$http.put('rest/Cate', this.model) : await this.$http.post('rest/Cate/add', this.model)
        if (res.status !== 200) {
          return this.$message.error(this.id ? '修改失败' : '添加失败')
        }
        res.data.inputVisible = false
        res.data.inputValue = ''
        this.id ? this.$store.commit('UpdataCate', res.data) : this.$store.commit('addCate', res.data)
        this.$message.success(this.id ? '修改成功' : '添加成功')
        window.sessionStorage.setItem('activePath', '/categories/list')
        this.$router.push('/categories/list')
      })
    },
    async fetch () {
      this.$http.get(`rest/Cate/${this.id}`).then(res => {
        if (res.status !== 200) {
          window.sessionStorage.setItem('activePath', '/categories/list')
          this.$router.push('/categories/list')
          return this.$message.error('获取分类信息失败')
        }
        this.model = res.data
      })
    }
  },
  created () {
    this.id && this.fetch()
  },
  watch: {
    '$route.path': function (newVal) {
      if (newVal === '/categories/create') {
        this.$data.model = { ...this.$options.data().model }
      }
    }
  }
}
</script>
